﻿using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Domain.Enums;
using QMERP.Infrastructure.CustomException;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;

namespace QMERP.Application.Services
{
    public class AttachmentService : IAttachmentService
    {
        private readonly IMapper _mapper;
        //private readonly ICache _cache;
        private readonly QMERPDbContext _db;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public AttachmentService(IMapper mapper, QMERPDbContext db, IWebHostEnvironment webHostEnvironment)
        {
            _mapper = mapper;
            _db = db;
            _webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<AttachmentResponse> UploadImage(AttachmentUploadRequest request)
        {
            try
            {
                if (request.File == null)
                {
                    throw new ApiException("文件接收异常!");
                }
                //图片文件校验 
                switch (request.File.ContentType)
                {
                    case "image/jpeg":
                        break;
                    case "image/png":
                        break;
                    default:
                        throw new ApiException("文件格式异常!");
                }
                string fileExtend = Path.GetExtension(request.File.FileName);

                string filePath = $"/FileStorage/{DateTime.Now:yyyyMMdd}/";

                string fileName = $"{Guid.NewGuid()}{fileExtend}";

                string rootPath = _webHostEnvironment.WebRootPath + filePath;

                if (!Directory.Exists(rootPath))
                {
                    Directory.CreateDirectory(rootPath);
                }

                using (FileStream fs = File.Create(rootPath + fileName))
                {
                    // 复制文件
                    request.File.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                Attachment attachment = new()
                {
                    OwnerId = request.OwnerId,
                    FileName = fileName,
                    SavePath = filePath + fileName,
                    FileExtend = fileExtend.Trim('.'),
                    FileSize = request.File.Length,
                    OwnerType = request.OwnerType
                };
                await _db.Attachment.AddAsync(attachment);
                await _db.SaveChangesAsync();
                return _mapper.Map<AttachmentResponse>(attachment);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 对应附件保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Save(AttachmentSaveRequest request)
        {
            var attachments = await _db.Attachment.Where(x => x.OwnerType == request.OwnerType && x.OwnerId == request.OwnerId && !request.AttachmentIds.Contains(x.Id)).ToListAsync();
            _db.RemoveRange(attachments);
            foreach (var attachmentId in request.AttachmentIds)
            {
                var attachment = await _db.Attachment.FindByIdAsync(attachmentId);
                if (attachment != null)
                {
                    if (attachment.OwnerId != null && attachment.OwnerId != request.OwnerId)
                    {
                        var model = new Attachment()
                        {
                            OwnerId = request.OwnerId,
                            OwnerType = attachment.OwnerType,
                            FileName = attachment.FileName,
                            FileExtend = attachment.FileExtend,
                            FileSize = attachment.FileSize,
                            SavePath = attachment.SavePath,
                            BasePath = attachment.BasePath,
                        };
                        await _db.AddAsync(model);
                    }
                    else
                    {
                        attachment.OwnerId = request.OwnerId;
                    }
                }
            }
            await _db.SaveChangesAsync();
        }
    }
}
